package com.itlong.cloud.controller.system;

import com.itlong.cloud.POJO.DTO.operate.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateUiInfoGetOneVO;
import com.itlong.cloud.POJO.VO.operate.OperateUiInfoGetPageVO;
import com.itlong.cloud.POJO.VO.operate.OperateUiProjectInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.OperateUiTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.noncore.commons.IUploadImageServiceClient;
import com.itlong.cloud.noncore.operate.IOperateUiManageServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Map;

/**
 * <desc>
 *      运营-UI管理控制器。
 * <desc/>
 *
 * @createDate 2018-03-19.
 */
@RestController
@RequestMapping("/system/uiManage")
@RefreshScope
public class OperateUIManageController extends BaseController {

    private  static final Logger LOG = LoggerFactory.getLogger(OperateUIManageController.class);

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    //UI操作接口
    @Autowired
    private IOperateUiManageServiceClient iOperateUiManageServiceClient;

    //上传图片
    @Autowired
    private IUploadImageServiceClient iUploadImageServiceClient;

    /**
     * <desc>
     *      上传文件
     * <desc/>
     *
     * @param stream 文件流
     * @return
     * @author shengen.T
     * @createDate 2018-03-20
     */
    private String uploadUIFile(InputStream stream,String fileType,String fileCatalog) throws Exception{
        //上传到ftp服务器
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                stream,
                fileType,
                FILE_ACCESS_URL,
                fileCatalog
        );
        Map<String, Object> resultMap = null;
        try {
            //LOG.info("正在上传UI文件");
            resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //LOG.info("上传完毕");
            if ("true".equals(resultMap.get("returnCode").toString())){
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            }
        }catch (Exception e){
            LOG.info("UI文件保存失败", e);
            return null;
        }finally {
            stream.close();
        }

        return null;
    }
    /**
     * <desc>
     *      添加UI。
     * <desc/>
     *
     * @param  saveDTO 保存参数
     * @return
     * @author shengen.T
     * @createDate 2018-03-19
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.SAVE_UI_INFO_LOG_DESC)
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object addUI(OperateUiInfoDTO saveDTO,HttpServletRequest request){
        MessageVO messageVO;
        saveDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateUiInfoDTO.class,request);
        try {
            //判断对象
            if(null == saveDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            saveDTO.setUiFile(multipartRequest.getFile("uiFile"));
            //判断UI名称
            if(StringUtils.isBlank(saveDTO.getUiName())){
                return new MessageVO(OperateErrorCodeEnum.UI_NAME_EMPTY_ERR.getErrorCode());
            }
            //判断关联项目
            if(StringUtils.isBlank(saveDTO.getProjectIds())){
                return new MessageVO(OperateErrorCodeEnum.UI_PROJECT_EMPTY_ERR.getErrorCode());
            }

            //判断UI类型
            if(!OperateUiTypeEnum.checkByUiType(saveDTO.getUiType())){
                return new MessageVO(OperateErrorCodeEnum.UI_TYPE_INVALID_ERR.getErrorCode());
            }

            //展示昵称
            if(StringUtils.isBlank(saveDTO.getShowName())){
                return new MessageVO(OperateErrorCodeEnum.UI_SHOW_NAME_EMPTY_ERR.getErrorCode());
            }

            long startTime = System.currentTimeMillis(); //程序开始记录时间
            System.out.print(String.format("开始上传UI：%s毫秒\t\n",startTime));
            OperateUiInfoSaveDTO operateUiInfoSaveDTO = new OperateUiInfoSaveDTO();
            //如果是物业类型
            if(OperateUiTypeEnum.UI_PROPERTY.getType().equals(saveDTO.getUiType())){
                //判断主题颜色
                if(StringUtils.isBlank(saveDTO.getUiBackground())){
                    return new MessageVO(OperateErrorCodeEnum.UI_BACKGROUND_ERR.getErrorCode());
                }
                //判断logo
                if(StringUtils.isBlank(saveDTO.getUiLogoUrl())){
                    return new MessageVO(OperateErrorCodeEnum.UI_LOGO_URL_EMPTY_ERR.getErrorCode());
                }
                operateUiInfoSaveDTO.setUiBackground(saveDTO.getUiBackground());
                operateUiInfoSaveDTO.setUiLogoUrl(saveDTO.getUiLogoUrl());
            }else {  // ios 和 android
                if (!ServletFileUpload.isMultipartContent(request)) {
                    return new MessageVO(OperateErrorCodeEnum.UI_FILE_INVALID_ERR.getErrorCode());
                }
                //判断UI文件
                if(saveDTO.getUiFile()==null){
                    return new MessageVO(OperateErrorCodeEnum.UI_FILE_INVALID_ERR.getErrorCode());
                }
                String path = uploadUIFile(((MultipartFile)saveDTO.getUiFile()).getInputStream(),"zip",FileCatalogEnum.UI_FILE.getType());
                if(StringUtils.isBlank(path)){
                    LOG.info("上传UI文件失败");
                    return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
                }
                operateUiInfoSaveDTO.setUiUrl(path);
            }
            long endTime  = System.currentTimeMillis(); //程序结束记录时间
            long TotalTime = endTime- startTime;       //总消耗时间
             System.out.print(String.format("上传UI耗时：%s毫秒\t\n",TotalTime));
            operateUiInfoSaveDTO.setUiType(saveDTO.getUiType());
            operateUiInfoSaveDTO.setUiName(saveDTO.getUiName());
            operateUiInfoSaveDTO.setRemark(saveDTO.getRemark());
            operateUiInfoSaveDTO.setProjectIds(saveDTO.getProjectIds());
            operateUiInfoSaveDTO.setShowName(saveDTO.getShowName());
            Integer result = iOperateUiManageServiceClient.saveUiInfo(operateUiInfoSaveDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_添加UI】添加UI失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      更新UI。
     * <desc/>
     *
     * @param  updateDTO 修改UI数据对象
     * @return
     * @author shengen.T
     * @createDate 2018-03-19
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.UPDATE_UI_INFO_LOG_DESC)
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object updateUI(OperateUiInfoDTO updateDTO,HttpServletRequest request){
        MessageVO messageVO;
        updateDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateUiInfoDTO.class,request);
        try {
            //判断对象
            if(null == updateDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            updateDTO.setUiFile(multipartRequest.getFile("uiFile"));
            //判断UI名称
            if(StringUtils.isBlank(updateDTO.getUiName())){
                return new MessageVO(OperateErrorCodeEnum.UI_NAME_EMPTY_ERR.getErrorCode());
            }
            //判断关联项目
            if(StringUtils.isBlank(updateDTO.getProjectIds())){
                return new MessageVO(OperateErrorCodeEnum.UI_PROJECT_EMPTY_ERR.getErrorCode());
            }
            //判断UI的Id
            if(StringUtils.isBlank(updateDTO.getUiId())){
                return new MessageVO(OperateErrorCodeEnum.UI_ID_EMPTY_ERR.getErrorCode());
            }
            //判断UI类型
            if(!OperateUiTypeEnum.checkByUiType(updateDTO.getUiType())){
                return new MessageVO(OperateErrorCodeEnum.UI_TYPE_INVALID_ERR.getErrorCode());
            }
            //展示昵称
            if(StringUtils.isBlank(updateDTO.getShowName())){
                return new MessageVO(OperateErrorCodeEnum.UI_SHOW_NAME_EMPTY_ERR.getErrorCode());
            }
            OperateUiInfoSaveDTO updateInfo = new OperateUiInfoSaveDTO();
            //如果是物业类型
            if(OperateUiTypeEnum.UI_PROPERTY.getType().equals(updateDTO.getUiType())){
                //判断主题颜色
                if(StringUtils.isBlank(updateDTO.getUiBackground())){
                    return new MessageVO(OperateErrorCodeEnum.UI_BACKGROUND_ERR.getErrorCode());
                }
                //判断logo
                if(StringUtils.isBlank(updateDTO.getUiLogoUrl())){
                    return new MessageVO(OperateErrorCodeEnum.UI_LOGO_URL_EMPTY_ERR.getErrorCode());
                }
                updateInfo.setUiBackground(updateDTO.getUiBackground());
                updateInfo.setUiLogoUrl(updateDTO.getUiLogoUrl());
            }else {  // ios 和 android
                //判断是否重新上传UI，重新上传则需要重新指定地址
                if(StringUtils.isBlank(updateDTO.getUiUrl())){
                    //判断UI文件
                    if(updateDTO.getUiFile()==null){
                        return new MessageVO(OperateErrorCodeEnum.UI_FILE_INVALID_ERR.getErrorCode());
                    }
                    String path = uploadUIFile(((MultipartFile)updateDTO.getUiFile()).getInputStream(),"zip",FileCatalogEnum.UI_FILE.getType());
                    if(StringUtils.isBlank(path)){
                        LOG.info("上传UI文件失败");
                        return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
                    }
                    updateInfo.setUiUrl(path);
                }
            }
            updateInfo.setUiId(updateDTO.getUiId());
            updateInfo.setUiType(updateDTO.getUiType());
            updateInfo.setUiName(updateDTO.getUiName());
            updateInfo.setRemark(updateDTO.getRemark());
            updateInfo.setProjectIds(updateDTO.getProjectIds());
            updateInfo.setShowName(updateDTO.getShowName());
            Integer result = iOperateUiManageServiceClient.updateUiInfo(updateInfo);
            messageVO = new MessageVO(updateDTO.getUiId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_更新UI】更新UI失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      删除UI。
     * <desc/>
     *
     * @param  uiIds 皮肤ID列表
     * @return
     * @author shengen.T
     * @createDate 2018-03-19
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.DELETE_UI_INFO_LOG_DESC)
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public Object deleteUI(String uiIds){
        MessageVO messageVO;
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        uiIds=request.getAttribute("uiIds")==null?null:request.getAttribute("uiIds").toString();
        try {
            //判断UI的Id
            if(StringUtils.isBlank(uiIds)){
                return new MessageVO(OperateErrorCodeEnum.UI_ID_EMPTY_ERR.getErrorCode());
            }
            iOperateUiManageServiceClient.delUiInfo(uiIds);
            messageVO = new MessageVO(uiIds,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_删除UI】删除UI失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      禁用启用。
     * <desc/>
     *
     * @param  uiId UI编号
     * @param  type  禁用/启用  1启用 2禁用
     * @return
     * @author shengen.T
     * @createDate 2018-03-26
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.SETSTATUS_UI_INFO_LOG_DESC)
    @RequestMapping(value = "setStatus", method = RequestMethod.POST)
    @ResponseBody
    public Object setStatus(String uiId,Integer type){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            uiId=request.getAttribute("uiId")==null?null:request.getAttribute("uiId").toString();
            type=request.getAttribute("type")==null?null:(Integer) request.getAttribute("type");
            //判断UI的Id
            if(StringUtils.isBlank(uiId)){
                return new MessageVO(OperateErrorCodeEnum.UI_ID_EMPTY_ERR.getErrorCode());
            }
            //判断禁用/启用类型
            if((!DataStatusEnum.NORMAL.getType().equals(type)) && (!DataStatusEnum.BAN.getType().equals(type))){
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            iOperateUiManageServiceClient.setStatus(uiId,type);
            messageVO = new MessageVO(uiId,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_启用/禁用】启用/禁用失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取UI详细信息。
     * <desc/>
     *
     * @param  uiId UI ID
     * @return
     * @author shengen.T
     * @createDate 2018-03-22
     */
    @RequestMapping(value = "getOne", method = RequestMethod.POST)
    @ResponseBody
    public Object getDetailUiInfo(String uiId){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            uiId=request.getAttribute("uiId")==null?null:request.getAttribute("uiId").toString();
            //判断皮肤ID
            if(StringUtils.isBlank(uiId)){
                return new MessageVO(OperateErrorCodeEnum.UI_ID_EMPTY_ERR.getErrorCode());
            }
            OperateUiInfoGetOneVO OneVO = iOperateUiManageServiceClient.getOneUiInfo(uiId);
            if(StringUtils.isBlank(OneVO.getRemark())){
              OneVO.setRemark("");
            }
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),OneVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_获取getOne】获取UI信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      分页获取UI信息。
     * <desc/>
     *
     * @param  pageDTO
     * @return
     * @author shengen.T
     * @createDate 2018-03-22
     */
    @RequestMapping(value = "getPage", method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getPageUiInfo(OperateUiInfoPageDTO pageDTO){
        MessageVO messageVO;
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        pageDTO=HttpProtocolUtil.parseRequestParamToDTO(OperateUiInfoPageDTO.class,request);
        try {
            Page<OperateUiInfoGetPageVO> pageVO = iOperateUiManageServiceClient.getPageUiInfo(pageDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),pageVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_获取getPage】获取UI分页信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取UI管理项目列表。
     * <desc/>
     *
     * @param  pageDTO
     * @return
     * @author shengen.T
     * @createDate 2018-03-22
     */
    @RequestMapping(value = "getPageProject", method = RequestMethod.POST)
    @ResponseBody
    public Object getPageProjectInfo(OperateProjectInfoGetPageDTO pageDTO){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO=HttpProtocolUtil.parseRequestParamToDTO(OperateProjectInfoGetPageDTO.class,request);
            //判断UI类型
            if(!OperateUiTypeEnum.checkByUiType(pageDTO.getType())){
                return new MessageVO(OperateErrorCodeEnum.UI_TYPE_INVALID_ERR.getErrorCode());
            }
            Page<OperateUiProjectInfoVO> pageVO = iOperateUiManageServiceClient.getPageProject(pageDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),pageVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_获取getPage】获取项目信息列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      上传logo。
     * <desc/>
     *
     * @param  httpServletRequest
     * @return
     * @author shengen.T
     * @createDate 2018-03-26
     */
    @RequestMapping(value = "uploadLogo", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadLogo(MultipartFile imgData, HttpServletRequest httpServletRequest){
        MessageVO messageVO;
        String imgUrl = ""; //返回图片链接地址
        String imgType ="";  //图片类型
        String imgExt = "jpg|jpeg|png|bmp|BMP|GIF|JPG|PNG|JPEG";
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) httpServletRequest;
            imgData = multipartRequest.getFile("imgData");
            //判断图片资源
            if(imgData==null){
                return new MessageVO(OperateErrorCodeEnum.IMAGE_RESOURCE_EMPTY_ERR.getErrorCode());
            }
            String imgName = imgData.getOriginalFilename();
            if(StringUtils.isBlank(imgName)){
                return new MessageVO(OperateErrorCodeEnum.IMAGE_RESOURCE_EMPTY_ERR.getErrorCode());
            }
            imgType = imgName.substring(imgName.lastIndexOf("."));
            //判断图片类型
            if(StringUtils.isBlank(imgType)||imgExt.contains(imgType)){
                return new MessageVO(OperateErrorCodeEnum.IMAGE_TYPE_ANVALID_ERR.getErrorCode());
            }
            imgUrl = uploadUIFile(imgData.getInputStream(),imgType,FileCatalogEnum.PROPERTY_UI_LOGO.getType());
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),"",imgUrl);
        }catch (Exception e){
            throw new DataAccessException("【运营_UI管理_上传logo】上传物业logo失败",e);
        }
        return messageVO;
    }
}
